package com.tdf.lolpanel.interceptor;


import com.tdf.lolpanel.constant.JwtConstant;
import com.tdf.lolpanel.constant.MsgConstant;
import com.tdf.lolpanel.constant.StatusConstant;
import com.tdf.lolpanel.context.BaseContext;
import com.tdf.lolpanel.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

/**
 * jwt令牌校验的拦截器
 */
@Slf4j
@Component
public class JwtTokenInterceptor implements HandlerInterceptor {


    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 校验jwt
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }

        //1、从请求头中获取令牌
        String token = request.getHeader(JwtConstant.tokenName);


        //2、校验令牌
        try {
//            log.info("jwt校验:{}", token);
            Claims claims = JwtUtils.parseJWT(JwtConstant.secretKey, token);
            Integer uid = Integer.valueOf(claims.get(JwtConstant.UID).toString());
            Integer status = Integer.valueOf(claims.get(JwtConstant.STATUS).toString());
            String uName = claims.get(JwtConstant.UNAME).toString();

            if (status.equals(StatusConstant.USR_DISABLE)) {
                throw new IllegalStateException(MsgConstant.ACCOUNT_LOCKED);
            }

            // 检查redis
            if (redisTemplate.opsForValue().get("jwt_" + uid) != null) {
                log.info("用户 \"{}\"(id：{}) 无法通过JWT", uName, uid);
                //4、不通过，响应401状态码
                response.setStatus(401);
                return false;
            }

            log.info("用户 \"{}\"(id：{}) 通过JWT", uName, uid);
            BaseContext.set(JwtConstant.UID, String.valueOf(uid));
            BaseContext.set(JwtConstant.STATUS, String.valueOf(status));
            BaseContext.set(JwtConstant.UNAME, uName);
            //3、通过，放行
            return true;
        } catch (Exception ex) {
            log.info("JWT校验失败: {}", ex.getMessage());
            //4、不通过，响应401状态码
            response.setStatus(401);
            return false;
        }
    }

}

